import openpyxl

wb_pinmux = openpyxl.load_workbook('pin_info.xlsx')
sh_info = wb_pinmux['pinmux']
cell_pins = list(sh_info.columns)[7][2:]

pin_idx = 1
pin_def_list = []
pin_obj_tbl_list = ['const machine_pin_obj_t* machine_pin_board_pins[] = ', '{']
pin_obj_dict_list = ['STATIC const mp_rom_map_elem_t machine_pin_board_pins_locals_dict_table[] =', '{']


for cell_pin in cell_pins:
    pin_name = cell_pin.value.strip().replace('-', '_N').replace('+', '_P')

    if pin_name[0] != 'P':
        print('NULL, /* %s */'%(pin_name))
        pin_obj_tbl_list.append('    NULL, /* %s */'%(pin_name))

    else:
        print(pin_name)
        pin_def_list.append('const machine_pin_obj_t pin_%s = { .base = { &machine_pin_type }, .name = MP_QSTR_%s, .gpio_port = GPIO%c, .gpio_pin = %s };'%(pin_name, pin_name, pin_name[1], pin_name[2:]))
        pin_obj_dict_list.append('    { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_PTR(&pin_%s) },'%(pin_name, pin_name))
        pin_obj_tbl_list.append('    &pin_%s,'%(pin_name))
    # print(pin_idx, pin_name)
    pin_idx = pin_idx + 1

pin_obj_tbl_list.append('};')
pin_obj_dict_list.append('};')

with open('machine_pin_board_pins_1.c', 'w') as f:
    f.write('#include "machine_pin.h"\n')
    f.write('#include "hal_common.h"\n\n')
    f.write('extern const mp_obj_type_t machine_pin_type;\n\n')
    f.write('const uint32_t machine_pin_board_pins_num = %d;\n\n'%(len(cell_pins)))
    for pin_obj in pin_def_list:
        f.write(pin_obj+'\n')
    f.write('\n')
    f.write('/* pin id in the package. */\n')
    for pin_obj in pin_obj_tbl_list:
        f.write(pin_obj+'\n')
    f.write('\n')
    for pin_obj in pin_obj_dict_list:
        f.write(pin_obj+'\n')
    f.write('\n')
    f.write('MP_DEFINE_CONST_DICT(machine_pin_board_pins_locals_dict, machine_pin_board_pins_locals_dict_table);\n\n\n')

